package com.mrd.gtimp.business.action;

import com.mrd.constant.BaseTypeConstant;
import com.mrd.constant.MsgConstants;
import com.mrd.framework.config.web.json.Result;
import com.mrd.framework.config.web.json.annotation.JField;
import com.mrd.framework.config.web.json.annotation.Json;
import com.mrd.framework.ui.Jqgrid;
import com.mrd.framework.ui.filter.Filter;
import com.mrd.framework.ui.filter.SearchRule;
import com.mrd.framework.ui.filter.SearchRuleOption;
import com.mrd.framework.utils.HttpUtils;
import com.mrd.gtimp.business.entity.Attachment;
import com.mrd.gtimp.business.entity.DeclarationOffer;
import com.mrd.gtimp.business.service.AttachmentBiz;
import com.mrd.gtimp.business.service.DeclarationOfferBiz;
import com.mrd.util.LoginUtil;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

/**
 * <p>
 * application name: gtimp
 * <p>
 * copyright: Copyright@2012 明睿达科技有限公司
 */

/**
 * @author yangyl
 */

@Controller
@RequestMapping("/business")
public class DeclarationOfferAction {
	private static final long	serialVersionUID	= 1L;

	@Resource
	private DeclarationOfferBiz	declarationOfferBiz;

	/**
	 * 返回前台的结果变量，格式为[[显示值，真实值],[显示值1，真实值1],...]
	 */
	private String[][]			results;
	@Resource
	private AttachmentBiz		attachmentBiz;

	/**
	 * 报关行报价主页面
	 */
	@RequestMapping("/declarationOffer-main")
	public String main() {
		return "/gtimp/declarationOffer/declarationOfferList";
	}

	/**
	 * 报关行报价修改页面
	 */
	@RequestMapping("/declarationOffer-declarationOfferManage")
	public String declarationOfferManage(String id,Model model) {
		model.addAttribute("id", id);
		return "/gtimp/declarationOffer/declarationOfferManage";
	}

	/**
	 * 平台审核报价主页面
	 */
	@RequestMapping("/declarationOffer-supMain")
	public String supMain() {
		return "/gtimp/declarationOffer/declarationOfferSupList";
	}

	/**
	 * 平台审核报价页面
	 */
	@RequestMapping("/declarationOffer-declarationOfferSupManage")
	public String declarationOfferSupManage(String id,ModelMap map) {
		map.put("id", id);
		return "/gtimp/declarationOffer/declarationOfferSupManage";
	}

	public Date priceEndTime(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(calendar.DATE, 1);
		calendar.add(calendar.SECOND, -1);
		return calendar.getTime();
	}

	/**
	 * 新增修改
	 */
	@RequestMapping("/declarationOffer-saveOrUpdate")
	@ResponseBody
	public Result saveOrUpdate(DeclarationOffer declarationOffer,String attaTempBillNo) {
		Result msg;
		try {
			//// TODO: 2016/9/1 没有成功提示
			if(StringUtils.isEmpty(declarationOffer.getId())) {// 新增
				declarationOffer.setId(null);
				declarationOffer.setReg_user(LoginUtil.getLoginUser().getAccount());
				declarationOffer.setRegDate(new Date());
				declarationOffer.setState(declarationOffer.getState());
				declarationOffer.setOwner(LoginUtil.getLoginUser().getCompany());
				if(declarationOffer.getPrice_end_time() != null) {
					declarationOffer
					        .setPrice_end_time(priceEndTime(declarationOffer.getPrice_end_time()));
				}
				if(BaseTypeConstant.DECLARATIONOFFERSTATE_01.equals(declarationOffer.getState())) {
					declarationOffer.setConfirm_user(LoginUtil.getLoginUser().getAccount());
					declarationOffer.setConfirmTime(new Date());
				}
				declarationOfferBiz.saveOrupdateEntity(declarationOffer);
				saveTempAttachment(declarationOffer, attaTempBillNo);
				msg = Result.newSuccessInstance(MsgConstants.SAVE_SUECCES);
			} else {// 修改
				List<String> properties = new ArrayList<String>();
				properties.add("declaration_amount");
				properties.add("imp_declaration_amount");
				properties.add("container_amount");
				properties.add("imp_container_amount");
				properties.add("price_begin_time");
				properties.add("price_end_time");
				properties.add("modi_date");
				properties.add("modi_user");
				properties.add("upload_id");
				properties.add("com_customs_code");
				properties.add("remark");
				properties.add("impRemark");
				properties.add("state");
				declarationOffer.setModi_date(new Date());
				declarationOffer.setModi_user(LoginUtil.getLoginUser().getAccount());
				if(declarationOffer.getPrice_end_time() != null) {
					declarationOffer
					        .setPrice_end_time(priceEndTime(declarationOffer.getPrice_end_time()));
				}
				declarationOfferBiz.updateEntity(declarationOffer, properties);
				saveTempAttachment(declarationOffer, attaTempBillNo);
				msg = Result.newSuccessInstance(MsgConstants.SAVE_SUECCES);
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg = Result.newFailInstance(MsgConstants.SAVE_FAIL);
		}
		return msg;
	}

	private void saveTempAttachment(DeclarationOffer declarationOffer,String attaTempBillNo)
	        throws Exception {
		if(StringUtils.isNotEmpty(attaTempBillNo)) {
			Filter filter = new Filter();
			filter.addRule(new SearchRule("bill_no", SearchRuleOption.eq, attaTempBillNo));
			List<Attachment> attachments = attachmentBiz.findEntityByFilter(0, 1, filter, null);
			attachments.forEach(atta -> {
				atta.setBill_no(declarationOffer.getId());
			});
			attachmentBiz.saveOrupdateEntity(attachments.get(0));
			// 这里在更新文件时有BUG
			// declarationOffer.setUpload_id(attachments.get(0));
			// declarationOfferBiz.saveOrupdateEntity(declarationOffer);
		} else if(declarationOffer.getId() != null) {
			throw new Exception("没有上传附件");
		}
	}

	/**
	 * 申报口岸下拉
	 */
	@RequestMapping("/declarationOffer-shenBaoPortName")
	@ResponseBody
	public List<DeclarationOffer> shenBaoPortName(@RequestParam(required = false) String k) {
		try {
			return declarationOfferBiz.findOfferPortOfCode(k);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 根据申报口岸获取报关行
	 */
	@RequestMapping("/declarationOffer-findDeclarationByPortName")
	@ResponseBody
	@Json({@JField("declaration_company_id"), @JField("declaration_company"),
	        @JField("com_customs_code") })
	public List<DeclarationOffer> findDeclarationByPortName() {
		List<DeclarationOffer> declarationOffers = new ArrayList<>();
		String port_code = HttpUtils.getParam("port_code");
		String hql = " from com.mrd.gtimp.business.entity.DeclarationOffer offer "
		        + "where offer.state='OS05' " + "and offer.port_code='" + port_code + "' "
		        + "and offer.price_begin_time <=  to_date('"
		        + new SimpleDateFormat("yyyy-MM-dd").format(new Date())
		        + "','yyyy-MM-dd') and offer.price_end_time >= to_date('"
		        + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "','yyyy-MM-dd')";
		// Filter filter = new Filter();
		// filter.addRule(new SearchRule("state", SearchRuleOption.eq, "OS05"));
		// filter.addRule(new SearchRule("port_code", SearchRuleOption.eq, port_code));
		// filter.addRule(new SearchRule("price_begin_time", SearchRuleOption.le, new Date()));
		// filter.addRule(new SearchRule("price_end_time", SearchRuleOption.gt, new Date()));
		declarationOffers = declarationOfferBiz.findEntityByHql(hql, 0, 1000, null);
		// try {
		// declarationOffers = declarationOfferBiz.findEntityByFilter(0, 1000, filter, null);
		// } catch (QueryException e) {
		// e.printStackTrace();
		// }
		if(declarationOffers != null && declarationOffers.size() > 0) {
			return declarationOffers;
		}
		return null;
	}

	/**
	 * 平台审核报关报价(通过或驳回)
	 */
	@RequestMapping("/declarationOffer-reviewPlatformFare")
	@ResponseBody
	public Result reviewPlatformFare(DeclarationOffer declarationOffer) {
		Result msg = null;
		if(StringUtils.isNotEmpty(declarationOffer.getId())) {
			try {
				if(BaseTypeConstant.DECLARATIONOFFERSTATE_03.equals(declarationOffer.getState())) {
					List<String> properties = new ArrayList<String>();
					properties.add("review_date");
					properties.add("review_user");
					properties.add("state");
					properties.add("review_reason");
					declarationOffer.setReview_date(new Date());
					declarationOffer.setReview_user(LoginUtil.getLoginUser().getAccount());
					declarationOfferBiz.updateEntity(declarationOffer, properties);
				} else if(BaseTypeConstant.DECLARATIONOFFERSTATE_02
				        .equals(declarationOffer.getState())) {
					int i = declarationOffer.getPrice_begin_time().compareTo(new Date());
					int j = declarationOffer.getPrice_end_time().compareTo(new Date());
					List<String> properties = new ArrayList<String>();
					properties.add("review_date");
					properties.add("review_user");
					properties.add("state");
					properties.add("review_reason");
					properties.add("port");
					properties.add("port_code");
					declarationOffer.setReview_date(new Date());
					declarationOffer.setReview_user(LoginUtil.getLoginUser().getAccount());
					if(i > 0) {
						declarationOffer.setState("OS05"); // 强制生效，至于在使用哪个报价的话，在查询报价时再进行区分
						declarationOffer.setPort(LoginUtil.getLoginUser().getCompany().getPort());
						declarationOffer
						        .setPort_code(LoginUtil.getLoginUser().getCompany().getPort_code());
						declarationOfferBiz.updateEntity(declarationOffer, properties);
					} else {
						if(j > 0) {// 立即生效报价，生效前将当前报价结束
							String sql = "update t_biz_declaration_offer t set t.state='OS04' where t.state='OS05' and t.declaration_company_id='"
							        + declarationOffer.getDeclaration_company_id() + "'";
							declarationOfferBiz.updateBySql(sql);
							declarationOffer.setState("OS05");
							declarationOffer
							        .setPort(LoginUtil.getLoginUser().getCompany().getPort());
							declarationOffer.setPort_code(LoginUtil.getLoginUser().getCompany()
							        .getPort_code());
							declarationOfferBiz.updateEntity(declarationOffer, properties);
						}
					}
				}
				msg = Result.newSuccessInstance(MsgConstants.SAVE_SUECCES);
			} catch (Exception e) {
				e.printStackTrace();
				msg = Result.newFailInstance(MsgConstants.SAVE_FAIL);
			}
		}
		return msg;
	}

	@RequestMapping("/declarationOffer-find")
	@ResponseBody
	@Json({@JField("id"), @JField("declaration_company"), @JField("declaration_amount"),
	        @JField("imp_declaration_amount"), @JField("container_amount"),
	        @JField("imp_container_amount"), @JField("price_begin_time"), @JField("price_end_time"),
	        @JField("state"), @JField("remark"), @JField("impRemark"), @JField("review_reason"),
	        @JField("upload_id.id"), @JField("declaration_company_id"),@JField("com_customs_code") })
	public DeclarationOffer find(DeclarationOffer declarationOffer) {
		String id = HttpUtils.getParam("id");
		if(StringUtils.isNotEmpty(id)) {
			try {
				declarationOffer = declarationOfferBiz.findEntityById(id);
				return declarationOffer;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 报价列表
	 */
	// public String findList() {//未改流程前方法
	// String com_type = user.getCompany().getType();
	// try {
	// if(filters == null) {
	// filters = new Filter();
	// filters.setGroupOp(FilterGroupOption.AND);
	// }
	// if("CC".equals(user.getCompany().getType())) {
	// SearchRule sr = new SearchRule("owner.id", SearchRuleOption.eq,
	// user.getCompany().getId());
	// filters.addRule(sr);
	// }
	// if("CM".equals(com_type)) {
	// SearchRule sr1 = new SearchRule("state", SearchRuleOption.ni,
	// BaseTypeConstant.DECLARATIONOFFERSTATE_00);
	// filters.addRule(sr1);
	// }
	// page = (initPage(declarationOfferBiz.findEntityCount(filters)));
	// declarationOffers =
	// declarationOfferBiz.findByJqgrid(page.getCurrentPageStartNo(),
	// page.getPageSize(), filters, null);
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// return "gridData";
	// }
	@RequestMapping("/declarationOffer-findList")
	@ResponseBody
	@Json({@JField("id"), @JField("declaration_company"), @JField("declaration_amount"),
	        @JField("container_amount"), @JField("imp_declaration_amount"),
	        @JField("imp_container_amount"), @JField("price_begin_time"), @JField("price_end_time"),
	        @JField("regDate"), @JField("reg_user"), @JField("modi_date"), @JField("modi_user"),
	        @JField("state"), @JField("confirmTime"), @JField("confirm_user"),
	        @JField("review_date"), @JField("review_user"), @JField("stateLabel") })
	public Page<DeclarationOffer> findList(Jqgrid jqgrid) {
		try {
			// if (filters == null) {
			// filters = new Filter();
			// filters.setGroupOp(FilterGroupOption.AND);
			// }
			// Order order = new Order();
			// if (null != sidx && !"".equals(sidx)) {
			// order.add(sidx, sord);
			// }
			// page = (initPage(declarationOfferBiz.findEntityCount(filters)));
			Page<DeclarationOffer> declarationOffers = declarationOfferBiz.findByJqgrid(jqgrid);
			declarationOfferBiz.beforePrintToPage(declarationOffers.getContent());
			if(declarationOffers.getSize() > 0) {
				return declarationOffers;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 报关行确认查询列表
	 */
	@RequestMapping("/declarationOffer-findSupList")
	@ResponseBody
	@Json({@JField("id"), @JField("declaration_company"), @JField("declaration_amount"),
	        @JField("container_amount"), @JField("imp_declaration_amount"),
	        @JField("imp_container_amount"), @JField("price_begin_time"), @JField("price_end_time"),
	        @JField("confirmTime"), @JField("confirm_user"), @JField("review_date"),
	        @JField("review_user"), @JField("state"), @JField("stateLabel") })
	public Page<DeclarationOffer> findSupList(Jqgrid jqgrid) {
		try {
			SearchRule sr = new SearchRule("declaration_company_id", SearchRuleOption.eq, LoginUtil
			        .getLoginUser().getCompany().getId());
			jqgrid.addRule(sr);
			SearchRule sr1 = new SearchRule("state", SearchRuleOption.ni, BaseTypeConstant.DECLARATIONOFFERSTATE_00
			        + "," + BaseTypeConstant.DECLARATIONOFFERSTATE_03);
			jqgrid.addRule(sr1);
			// page = (initPage(declarationOfferBiz.findEntityCount(filters)));
			// Order order = new Order();
			// order.add("confirm_time", true);
			Page<DeclarationOffer> declarationOffers = declarationOfferBiz.findByJqgrid(jqgrid);
			if(declarationOffers != null && declarationOffers.getSize() > 0) {
				return declarationOffers;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 提交报价
	 */
	@RequestMapping("/declarationOffer-confirm")
	@ResponseBody
	public Result confirm() {
		Result msg;
		String id = HttpUtils.getParam("id");
		try {
			DeclarationOffer declarationOffer = declarationOfferBiz.findEntityById(id);
			List<String> properties = new ArrayList<String>();
			properties.add("confirm_user");
			properties.add("confirm_time");
			properties.add("state");
			declarationOffer.setConfirm_user(LoginUtil.getLoginUser().getAccount());
			declarationOffer.setConfirmTime(new Date());
			declarationOffer.setState(BaseTypeConstant.DECLARATIONOFFERSTATE_01);
			declarationOfferBiz.updateEntity(declarationOffer, properties);
			msg = Result.newSuccessInstance(MsgConstants.OPERATION_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
		}
		return msg;
	}

	// 3.0报价查询方法
	@RequestMapping("/declarationOffer-getDeclarationOfferFree")
	@ResponseBody
	@Json({@JField("declaration_amount"), @JField("imp_declaration_amount"),@JField("impRemark"),
	        @JField("container_amount"), @JField("imp_container_amount"), @JField("remark") })
	public DeclarationOffer getDeclarationOfferFree(DeclarationOffer declarationOffer) {
		if(declarationOffer == null
		        || StringUtils.isEmpty(declarationOffer.getDeclaration_company_id())) {
			return declarationOffer;
		}
		return declarationOfferBiz.findValidOffer(declarationOffer.getDeclaration_company_id());
	}

}
